package org.zfes.snowier.zbss.xzy;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import org.zfes.snowier.core.util.UUIDUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.core.util.ZWebUtil;
import org.zfes.snowier.core.util.encypt.RSAUtil;

import com.google.common.base.Splitter;

public class ParamUtil {
//	=========播放过程=============
//			1===========云端准备
//			midiaUrl
//			liveid：
//			us=uuid
//			KEY：流媒体服务器rsa私钥
//
//			appid：1515115154
//			appKey：uuid
//			rsaPrivateKey：
//			rsaPublicKey：
//			2===========云端签名
//			sign = rsaSign(appKey + liveid + t + exper + us)
//
//			3============云端生成播放地址，给移动端
//			signParam="t="+hexTime+"&us="+us
//			playUrl = mediaUrl+"?"+appId="appid"+signParam+"&sign="+sign;
//
//			4============移动端 验证playUrl 播放请求
//			流媒体 验证playUrl ，开放视频流
	
	public static String mapToUrl(Map<String,String> params) {
		StringBuilder stringBuilder = new StringBuilder();
		 Map<String, String> treeMap = new TreeMap<>();
		 treeMap.putAll(params);
        for (Map.Entry<String, String> s : treeMap.entrySet()) {
            String key = s.getKey();
            String value = s.getValue();
            if (ZStrUtil.hasNoText(value)) {
                continue;
            }
            stringBuilder.append(key).append("=").append(value).append("&");
        }
        return stringBuilder.toString();
	}
	
	//?a=b&c=d&s
	//"?"+appId="appid"+signParam+"&sign="+sign;
	public static String sortUrlParm(String paramStr) {
		Map<String,String> params =Arrays.asList(paramStr.split("&")).stream().filter(v->ZStrUtil.hasText(v))
				.collect(Collectors.toMap(key->key.split("=")[0], val->val.split("=")[1]));
		System.out.println(params);
		Map<String, String> treeMap = new TreeMap<>();
		treeMap.putAll(params);
		treeMap.remove("sign");
		 
		StringBuilder stringBuilder = new StringBuilder();
		 treeMap.putAll(params);
        for (Map.Entry<String, String> s : treeMap.entrySet()) {
            String key = s.getKey();
            String value = s.getValue();
            if (ZStrUtil.hasNoText(value)) {
                continue;
            }
            stringBuilder.append(key).append("=").append(value).append("&");
        }
        //stringBuilder.append("scretId="+scretId);
        return ZStrUtil.substringBeforeLast(stringBuilder.toString(), "&");
	}
	
	public static String sign(String rasPrivateKey,String paramStr,String scretId) {
		return RSAUtil.sign(appendScretId(sortUrlParm( paramStr), scretId).getBytes(), rasPrivateKey,true);
	}
	
	
	public static boolean verify(String rasPublicKey,String scretId,String paramStr,String sign) {
		return RSAUtil.verify(appendScretId(sortUrlParm(paramStr), scretId).getBytes(), rasPublicKey,sign,true);
	}
	
	public static String appendScretId(String sortedUrl,String scretId) {
		return sortedUrl+"&scretId="+scretId;
	}
	public static String getParam(String url, String name) {
	    String params = url.substring(url.indexOf("?") + 1, url.length());
	    Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
	    return split.get(name);
	}
	
	public static void main(String[] args) {
		  Map<String, Object> keyMap = RSAUtil.genKeyPair();
	  	    String publicKey = RSAUtil.getPublicKey(keyMap);
	  	    String privateKey = RSAUtil.getPrivateKey(keyMap);
	  	    
		String us=UUIDUtil.fastUUID();
		String appId="1515115154";
		String liveId="abacdedf";
		Long expreTime =System.currentTimeMillis()+6*60*1000; 
		String url="http://sadasd.com/live/"+liveId+".flv?appId="+appId+"&us="+us+"&t="+expreTime+"";
		
		
		String scretId="koaisdjauifhsdghygfuishfzkusf";
		String urlParam=ZStrUtil.substringAfter(url, "?");
		String sgin=sign(privateKey,urlParam, scretId);
		url=url+"&sign="+sgin;
		System.out.println(url);
		System.out.println("=================================");
		
		String sign=getParam( url,  "sign") ;
		
		String paramStr=new String(urlParam);//
		String sortedParamUrl=sortUrlParm(paramStr);
		
		Boolean v=verify(publicKey, scretId, sortedParamUrl, sign);
		
		System.out.println(v);
	}
	
}
